<?php

namespace app\modules\sysConfig\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\sysConfig\models\Sms;
use app\modules\lenders\models\Lender;
use app\modules\lenders\models\Lendinvestment;
use app\modules\borrowers\models\Borrower;

/**
 * SmsSearch represents the model behind the search form about `app\modules\sysConfig\models\Sms`.
 */
class SmsSearch extends Sms {

    public $lender_userName; //理财客户
    public $borrower_userName; //借款客户
    public $lender_companyName; //投资部门
    public $lender_phone; //联系电话
    public $lender_IDType; //身份证类型
    public $lender_identityNo; //身份证号码
    public $lender_accountStatus; //账户状态
    public $lender_customerManagerName; //客户经理
    public $lender_strcreateTime; //创建开始时间
    public $lender_endcreateTime; //创建开始时间

    /**
     * @inheritdoc
     */

    public function rules() {
        return [
            [['smsID'], 'integer'],
            [['smsType', 'phones', 'borrower_userName', 'lender_userName', 'lender_IDType', 'lender_companyName', 'lender_phone', 'lender_identityNo', 'lender_userName', 'lender_accountStatus', 'lender_customerManagerName', 'lender_strcreateTime', 'lender_endcreateTime', 'body', 'createTime', 'createUser', 'responseCode', 'smsCode'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params) {
        $query = Sms::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'smsID' => $this->smsID,
            'createTime' => $this->createTime,
        ]);

        $query->andFilterWhere(['like', 'smsType', $this->smsType])
                ->andFilterWhere(['like', 'phones', $this->phones])
                ->andFilterWhere(['like', 'body', $this->body])
                ->andFilterWhere(['like', 'createUser', $this->createUser])
                ->andFilterWhere(['like', 'responseCode', $this->responseCode])
                ->andFilterWhere(['like', 'smsCode', $this->smsCode]);

        return $dataProvider;
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function searchSms($params) {
        if (!($this->load($params) && $this->validate())) {//判断为空就返回
            $this->phones = '';
            $this->lender_count = 0;
        }
        if ($this->smsType == '1') {//判断是理财客户还是借款客户
            //查询公司Lendinvestment表
            if (!empty($this->lender_companyName)) {
                $lendinves = Lendinvestment::find();
                $dataProvider = new ActiveDataProvider([
                    'query' => $lendinves,
                ]);
                $lendinves->select('(lenderID)');
                $company = explode('/', $this->lender_companyName);
                $lendinves->andFilterWhere(['in', 'companyName', $company]);
            }
            //查询lender表
            $lender = Lender::find(); //理财客户
            $lender->select('lenderID'); //理财客户
             $dataProvider = new ActiveDataProvider([
                    'query' => $lender,
                ]);
            //创建时间查询
            if (!empty($this->lender_endcreateTime) && !empty($this->lender_strcreateTime)) {
                $data_star = date("Y-m-d H:i:s", strtotime($this->lender_strcreateTime . "00:00:00"));
                $data_end = date("Y-m-d H:i:s", strtotime($this->lender_endcreateTime . "23:59:59"));
                $lender->andFilterWhere(['>=', 'createTime', $data_star]);
                $lender->andFilterWhere(['<=', 'createTime', $data_end]);
            }
            //查询
            $lender->andFilterWhere([
                'IDType' => $this->lender_IDType,
                'accountStatus' => $this->lender_accountStatus,
            ]);
            //查询方式
            $lender->andFilterWhere(['like', 'userName', $this->lender_userName])
                    ->andFilterWhere(['like', 'phone', $this->lender_phone])
                    ->andFilterWhere(['like', 'customerManagerName', $this->lender_customerManagerName])
                    ->andFilterWhere(['like', 'identityNo', $this->lender_identityNo]);

            //查询公司不为空 对比Lendinvestment 和lender 表数据 取到 lenderID
            if (!empty($this->lender_companyName)) {
//                $lender->andFilterWhere(['in', 'lenderID', $lendinvesArray]);
                $commandQuery = clone $lendinves;
//                
                $res = $commandQuery->createCommand()->queryAll();
                $lendinvesArray = [];
                if (isset($res)) {
                    foreach ($res as $value) {
                        array_push($lendinvesArray, $value['lenderID']);
                    }
                    //去重复
                    $array = array_unique($lendinvesArray);
                    $lender->andFilterWhere(['in', 'lenderID', $array]);
                    $commandQuery = clone $lender;
                }
            } else {
                $commandQuery = clone $lender;
            }
            //转换成sql
//            $sql = $commandQuery->createCommand()->getRawSql();
            //执行sql
//            var_dump(($sql));
            $res = $commandQuery->createCommand()->queryAll();
            foreach ($res as $value) {
//                var_dump($value['lenderID']);
                $lenderPhone = Lender::findOne($value['lenderID']);
                if (isset($lenderPhone)) {
                    $this->phones .= $lenderPhone->phone . ',';
                }
            }
        } else {//借款客户
            $borrower = Borrower::find();
            
            $borrower->select('phone'); //理财客户
             $dataProvider = new ActiveDataProvider([
                    'query' => $borrower,
                ]);
            //创建时间查询
            if (!empty($this->lender_endcreateTime) && !empty($this->lender_strcreateTime)) {
                $data_star = date("Y-m-d H:i:s", strtotime($this->lender_strcreateTime . "00:00:00"));
                $data_end = date("Y-m-d H:i:s", strtotime($this->lender_endcreateTime . "23:59:59"));
                $borrower->andFilterWhere(['>=', 'createTime', $data_star]);
                $borrower->andFilterWhere(['<=', 'createTime', $data_end]);
            }
            //查询
            $borrower->andFilterWhere([
                'accountStatus' => $this->lender_accountStatus,
            ]);
            //查询方式
            $borrower->andFilterWhere(['like', 'userName', $this->borrower_userName])
                    ->andFilterWhere(['like', 'phone', $this->lender_phone])
                    ->andFilterWhere(['like', 'identityNo', $this->lender_identityNo
            ]);
            $commandQuery = clone $borrower;
            //转换成sql
            $sql = $commandQuery->createCommand()->getRawSql();
            //执行sql
            var_dump(($sql));
            $res = $commandQuery->createCommand()->queryAll();
            foreach ($res as $value) {
                if (!empty($value['phone'])) {
                    $this->phones .= $value['phone'] . ',';
                }
            }
        }
        //创建txt 文本
        $path = Yii::getAlias('@backend/web/phonesms');
//            var_dump($path);die;
        if (!is_dir($path)) {
            mkdir($path, 0777);  // 创建文件夹test,并给777的权限（所有权限）
        }
        $content = $this->phones;  // 写入的内容
        $wenjian = '/phone' . time() . ".txt";
        $file = $path . $wenjian;  // 写入的文件
        file_put_contents($file, $content, FILE_APPEND);
        $lujing = 'http://' . $_SERVER['HTTP_HOST'] . '/phonesms' . $wenjian;
        $this->phones = $lujing;
        $this->lender_count = count($res);
    }

}
